#include "core/submodule_rewriter.h"
#include <iostream>
#include <fstream>
#include <sstream>

SubmoduleRewriter::SubmoduleRewriter(const std::string& git_path) 
    : git_path_(git_path) {
    initDefaultMirrors();
}

void SubmoduleRewriter::initDefaultMirrors() {
    // GitHub 到 Gitee 的映射
    mirror_map_ = {
        {"github.com/wxWidgets/", "gitee.com/uesoft/"},
        {"github.com/PhilipHazel/", "gitee.com/uesoft/"},
        {"github.com/madler/", "gitee.com/uesoft/"},
        {"github.com/libexpat/", "gitee.com/uesoft/"}
    };
}

bool SubmoduleRewriter::loadGitmodules(const std::string& repo_path) {
    repo_path_ = repo_path;
    std::string gitmodules_path = repo_path + "/.gitmodules";
    return parseGitmodulesFile(gitmodules_path);
}

bool SubmoduleRewriter::parseGitmodulesFile(const std::string& file_path) {
    std::ifstream file(file_path);
    if (!file.is_open()) {
        std::cout << "❌ Cannot open: " << file_path << std::endl;
        return false;
    }
    
    submodules_.clear();
    SubmoduleConfig current;
    std::string line;
    
    while (std::getline(file, line)) {
        if (line.find("[submodule") != std::string::npos) {
            if (!current.name.empty()) {
                submodules_.push_back(current);
                current = SubmoduleConfig();
            }
            // 提取子模块名称
            size_t start = line.find('"');
            size_t end = line.rfind('"');
            if (start != std::string::npos && end != std::string::npos) {
                current.name = line.substr(start + 1, end - start - 1);
            }
        } else if (line.find("path =") != std::string::npos) {
            current.path = line.substr(line.find('=') + 1);
            // 去除前后空格
            current.path.erase(0, current.path.find_first_not_of(" \t"));
            current.path.erase(current.path.find_last_not_of(" \t") + 1);
        } else if (line.find("url =") != std::string::npos) {
            current.url = line.substr(line.find('=') + 1);
            current.url.erase(0, current.url.find_first_not_of(" \t"));
            current.url.erase(current.url.find_last_not_of(" \t") + 1);
        } else if (line.find("branch =") != std::string::npos) {
            current.branch = line.substr(line.find('=') + 1);
            current.branch.erase(0, current.branch.find_first_not_of(" \t"));
            current.branch.erase(current.branch.find_last_not_of(" \t") + 1);
        }
    }
    
    // 添加最后一个子模块
    if (!current.name.empty()) {
        submodules_.push_back(current);
    }
    
    std::cout << "✅ Parsed " << submodules_.size() << " submodules from " << file_path << std::endl;
    return true;
}

bool SubmoduleRewriter::rewriteToMirrors() {
    bool changed = false;
    for (auto& submodule : submodules_) {
        std::string new_url = rewriteUrl(submodule.url);
        if (new_url != submodule.url) {
            std::cout << "🔧 Rewriting: " << submodule.url << " -> " << new_url << std::endl;
            submodule.url = new_url;
            changed = true;
        }
    }
    return changed;
}

std::string SubmoduleRewriter::rewriteUrl(const std::string& original_url) {
    for (const auto& mapping : mirror_map_) {
        if (original_url.find(mapping.first) != std::string::npos) {
            std::string new_url = original_url;
            size_t pos = new_url.find(mapping.first);
            if (pos != std::string::npos) {
                new_url.replace(pos, mapping.first.length(), mapping.second);
                return new_url;
            }
        }
    }
    return original_url;
}

bool SubmoduleRewriter::applyChanges() {
    if (repo_path_.empty()) {
        std::cout << "❌ No repository path set" << std::endl;
        return false;
    }
    return writeGitmodulesFile(repo_path_ + "/.gitmodules");
}

bool SubmoduleRewriter::writeGitmodulesFile(const std::string& file_path) {
    std::ofstream file(file_path);
    if (!file.is_open()) {
        std::cout << "❌ Cannot write to: " << file_path << std::endl;
        return false;
    }
    
    for (const auto& submodule : submodules_) {
        file << "[submodule \"" << submodule.name << "\"]\n";
        file << "    path = " << submodule.path << "\n";
        file << "    url = " << submodule.url << "\n";
        if (!submodule.branch.empty()) {
            file << "    branch = " << submodule.branch << "\n";
        }
        file << "\n";
    }
    
    std::cout << "✅ Updated: " << file_path << std::endl;
    return true;
}

void SubmoduleRewriter::addMirrorMapping(const std::string& source, const std::string& target) {
    mirror_map_[source] = target;
}
